<?php
namespace app\admin\controller;
use think\Db;
class Goods extends Base
{
    //列表
    public function lists()
    {
        if(is_post()){
            $cur_page     = input('page');
            $keyword  = input('keyword');
            $status  = input('status');
            $cat_id  = input('cat_id');
            $rec_id  = input('rec_id');
            $min_time = input('min_time');
            $max_time = input('max_time');
            $sql = "
                select
                    [1]
                from
                    goods a
                left join
                    goods_cat b
                on
                    a.cat_id = b.id
                ";
            $param = [];
            $w = ['where'];
            if(!empty($min_time)){
                $w[] = ' and a.create_time>?';
                $param[] = strtotime($min_time);
            }
            if(!empty($max_time)){
                $w[] = ' and a.create_time<?';
                $param[] = strtotime($max_time);
            }
            if(!empty($keyword)){
                $w[] = ' and a.title like ?';
                $param[] = "%{$keyword}%";
            }
            if($status!='100all'){
                $w[] = ' and a.status = ?';
                $param[] = $status;
            }
            if($cat_id!='100all'){
                $w[] = ' and a.cat_id = ?';
                $param[] = $cat_id;
            }
            if($rec_id!='100all'){
                $w[] = ' and a.rec_id = ?';
                $param[] = $rec_id;
            }
            #条件判断
            if (count($w)>1){
              $w[1] = str_replace("and","",$w[1]);
              $sql .= implode(" ",$w);
            }
            #分页
            $page_size = c('a.page_size');
            $page_html = com_list_page($sql, $param, $cur_page,$page_size);

            #内容
            $start = ($cur_page - 1) * $page_size;
            $field = "a.*,b.cat_title";
            $sql_list = str_replace("[1]",$field,$sql);
            $sql_list .= " order by a.sort desc, a.id desc limit {$start},{$page_size}";
            $rslist = Db::query($sql_list, $param);
            $rec = ['0'=>'无推荐位'] + Db::name("goods_rec")->where("status",0)->order("sort desc,id desc")->column('title','id');
            foreach ($rslist as $k => $v) {
                $rslist[$k]['create_time'] = com_formate_time($v['create_time']);
                $rslist[$k]['checkbox'] = com_checkbox($v['id']);
                $rslist[$k]['rec_id'] = "<select tid='{$v['id']}' onchange='change(this)'>";
                foreach($rec as $key => $val){
                  $checked = $key==$v['rec_id'] ? "selected" : "";
                  $rslist[$k]['rec_id'] .= "<option value='{$key}' $checked>{$val}</option>";
                }
                $rslist[$k]['rec_id'] .= "</select>";
                $rslist[$k]['pic'] = $v['pic'] ? "<img src='{$v['pic']}' height=50 />" : "";
                $rslist[$k]['sort']   = com_sort('goods',$v['id'],$v['sort']);
                $rslist[$k]['status'] = c('type.status',$v['status']);
                $rslist[$k]['action']  = com_btn_edit("/goods/edit/id/{$v['id']}");
                $rslist[$k]['action']  .= com_copy('goods',$v['id']);
                $rslist[$k]['action']  .= com_btn_del("/goods/delete/id/{$v['id']}", "您确定要删除【{$v['title']}】？");
            }
            $body_html = com_list_body($rslist, ["checkbox","pic","title","cat_title","rec_id","sort", "status", "create_time", "action"]);
            com_check(['data'=>['com_body'=>$body_html, 'com_page'=>$page_html]]);
        }
        $all= [
            '100all' => [
                'id' => '100all',
                'parent_id' => 0,
                'cat_title' => '全部分类',
                'depath' => 0,
                ]
        ];
        $catlist = $all + \app\admin\model\GoodsCat::allSubCat();
        $rec = ['100all'=>'全部推荐'] + Db::name("goods_rec")->where("status",0)->order("sort desc,id desc")->column('title','id');
        return view('',['status'=>c('type.status'),'catlist'=>$catlist,'rec'=>$rec]);
    }
    //套餐选项的列表
    public function glists()
    {
        if(is_post()){
            $cur_page     = input('page');
            $keyword  = input('keyword');
            $status  = input('status');
            $cat_id  = input('cat_id');
            $rec_id  = input('rec_id');
            $min_time = input('min_time');
            $max_time = input('max_time');
            $sql = "
                select
                    [1]
                from
                    goods a
                left join
                    goods_cat b
                on
                    a.cat_id = b.id
                ";
            $param = [];
            $w = ['where'];
            if(!empty($min_time)){
                $w[] = ' and a.create_time>?';
                $param[] = strtotime($min_time);
            }
            if(!empty($max_time)){
                $w[] = ' and a.create_time<?';
                $param[] = strtotime($max_time);
            }
            if(!empty($keyword)){
                $w[] = ' and a.title like ?';
                $param[] = "%{$keyword}%";
            }
            if($status!='100all'){
                $w[] = ' and a.status = ?';
                $param[] = $status;
            }
            if($cat_id!='100all'){
                $w[] = ' and a.cat_id = ?';
                $param[] = $cat_id;
            }
            if($rec_id!='100all'){
                $w[] = ' and a.rec_id = ?';
                $param[] = $rec_id;
            }
            #条件判断
            if (count($w)>1){
              $w[1] = str_replace("and","",$w[1]);
              $sql .= implode(" ",$w);
            }
            #分页
            $page_size = 5;
            $page_html = com_list_page($sql, $param, $cur_page,$page_size);

            #内容
            $start = ($cur_page - 1) * $page_size;
            $field = "a.*,b.cat_title";
            $sql_list = str_replace("[1]",$field,$sql);
            $sql_list .= " order by a.sort desc, a.id desc limit {$start},{$page_size}";
            $rslist = Db::query($sql_list, $param);
            $rec = ['0'=>'无推荐位'] + Db::name("goods_rec")->where("status",0)->order("sort desc,id desc")->column('title','id');
            foreach ($rslist as $k => $v) {
                $rslist[$k]['create_time'] = com_formate_time($v['create_time']);
                $rslist[$k]['checkbox'] = com_checkbox($v['id']);
                $rslist[$k]['rec_id'] = "<select tid='{$v['id']}' onchange='change(this)'>";
                foreach($rec as $key => $val){
                  $checked = $key==$v['rec_id'] ? "selected" : "";
                  $rslist[$k]['rec_id'] .= "<option value='{$key}' $checked>{$val}</option>";
                }
                $rslist[$k]['rec_id'] .= "</select>";
                $rslist[$k]['pic'] = $v['pic'] ? "<img src='{$v['pic']}' height=50 />" : "";
                $rslist[$k]['sort']   = com_sort('goods',$v['id'],$v['sort']);
                $rslist[$k]['status'] = c('type.status',$v['status']);
              $rslist[$k]['action']  = '<a class="layui-btn layui-btn-mini layui-btn-primary" href="javascript:addgoods('.$v['id'].',\''.$v['title'].'\')">添加到套餐<a>';
            }
            $body_html = com_list_body($rslist, ["pic","title","cat_title", "status", "create_time", "action"]);
            com_check(['data'=>['com_body'=>$body_html, 'com_page'=>$page_html]]);
        }
    }
    //选择分类添加产品
    function addbycat(){
        if(is_post()){
            $id = input('cat_id');
            com_check(['suc_url'=>url('goods/add','cid='.$id)]);
        }
        $all= [
            '100all' => [
                'id' => '',
                'parent_id' => 0,
                'cat_title' => '请选择分类',
                'depath' => 0,
                ]
        ];
        $catlist = $all + \app\admin\model\GoodsCat::allSubCat();
        return view('',['catlist'=>$catlist]);
    }
    #添加
    function add($cid=''){
      if(is_post()){
            $d = post();
            $rule = [
                'title'=>  'require',
                'pic'=>  'require',
                'spec'=>  'require',
                'rmb'=>  'require|number',
                'stock'=>  'require|number',
            ];
            $msg = [
              'title.require'   =>  '请输入标题',
              'spec.require'   =>  '请输入规格',
              'pic.require'   =>  '请输入上传封面图',
              'rmb.require'   =>  '请输入售价',
              'rmb.number'   =>  '请输入数字',
              'stock.require'   =>  '请输入库存数',
              'stock.number'   =>  '请输入数字',
            ];
            com_validate($rule, $msg, $d);
            if(isset($d['attr'])) $d['attr'] = json_encode($d['attr']);
            $d['create_time'] = time();
            $d['update_time'] = time();
            Db::name("goods")->insert($d);
            com_check(['suc_msg'=>'添加成功!','suc_js'=>'alert|close|reload']);
      }
      $cat = Db::name('goods_cat')->find($cid);
      $attr = Db::name('goods_cat_attr')->where("status",0)->where('goods_cat_id',$cid)->order("sort desc")->select();
      return view('',['cat'=>$cat,'attr'=>$attr]);
    }

    #编辑
    function edit($id=''){
      if(is_post()){
            $d = post();
            $rule = [
                'title'=>  'require',
                'spec'=>  'require',
                'pic'=>  'require',
                'rmb'=>  'require|number',
                'stock'=>  'require|number',
            ];
            $msg = [
              'title.require'   =>  '请输入标题',
              'spec.require'   =>  '请输入规格',
              'pic.require'   =>  '请输入上传封面图',
              'rmb.require'   =>  '请输入售价',
              'rmb.number'   =>  '请输入数字',
              'stock.require'   =>  '请输入库存数',
              'stock.number'   =>  '请输入数字',
            ];
            com_validate($rule, $msg, $d);
            $d['attr'] = json_encode($d['attr']);
            $d['update_time'] = time();
            Db::name("goods")->update($d);
            com_check(['suc_msg'=>'修改成功!','suc_js'=>'alert|close|reload']);
      }
      $info = Db::name('goods')->find($id);
      $info_attr = json_decode($info['attr'],true);
      $cat = Db::name('goods_cat')->find($info['cat_id']);
      $attr = Db::name('goods_cat_attr')->where("status",0)->where('goods_cat_id',$info['cat_id'])->order("sort desc")->select();
      return view('',['info'=>$info,'status'=>c('type.status'),'cat'=>$cat,'attr'=>$attr,'info_attr'=>$info_attr]);
    }
    #设置推荐位
    function rec(){
        if(is_post()){
          $d = post();
          Db::name('goods')->update($d);
          com_check(['suc_msg'=>'设置成功!','suc_js'=>'alert|close|reload']);
        }
    }

    #删除
    function delete($id){
      $rs = Db::query("select id from goods_package where goods_ids like ?",["%\"{$id}\"%"]);
      if($rs){
        com_error('已有套餐使用该产品,不能删除!');
      }else{
        Db::name('goods')->delete($id);
      }
      com_check(['suc_msg'=>'删除成功!','suc_js'=>'alert|close|reload']);
    }

    #批量删除
    function delall(){
      if(is_post()){
          $ids = input('ids/a');
          foreach($ids as $id){
            $rs = Db::query("select id from goods_package where goods_ids like ?",["%\"{$id}\"%"]);
            if($rs){
              com_error('已有套餐使用该产品,不能删除!');
            }else{
              Db::name('goods')->delete($id);
            }
          }
          com_check(['suc_msg'=>'删除成功!','suc_js'=>'alert|close|reload']);
      }
    }
}
